package com.ruanhb.wsp.service;

import com.alibaba.fastjson.JSON;
import com.ruanhb.wsp.vo.BaseResponse;
import com.ruanhb.wsp.vo.Weather;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * Created by r on 2018-9-21
 */
@Service
@Slf4j
public class WeatherDataServiceImpl implements WeatherDataService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public BaseResponse<Weather> getWeatherDataByCityId(String cityId) {

        String key = "http://wthrcdn.etouch.cn/weather_mini" + "?citykey="+cityId;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        // 先查缓存，缓存有的取缓存中的数据
        if (stringRedisTemplate.hasKey(key)) {
            strBody = ops.get(key);
            log.info("redis has data 【{}】",strBody);
        } else {
            log.info("redis don't has data");
            //缓存没有，抛出异常
            throw new RuntimeException("don't has data");
        }
        BaseResponse baseResponse =  JSON.parseObject(strBody, BaseResponse.class);
        return baseResponse;
    }
}
